package com.shopcart.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.shopcart.controller.CartController;
import com.shopcart.entity.Customer;

@WebServlet("/CartServlet")
public class CartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public CartServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map params = request.getParameterMap();
		Set<?> keySet = params.keySet();
		Iterator<?> itr = keySet.iterator();

		List<Long> idList = new ArrayList<Long>();
		List<Integer> countList = new ArrayList<Integer>();

		while (itr.hasNext()) {
			String key = (String) itr.next();

			if (key.contains("idList")) {
				for (String idValue : (String[]) params.get(key)) {
					idList.add(Long.valueOf(idValue));
				}
			} else if (key.contains("countList")) {
				for (String countValue : (String[]) params.get(key)) {
					countList.add(Integer.parseInt(countValue));
				}
			}
		}
		
		HttpSession session = request.getSession();
		CartController cc = (CartController) session.getAttribute("cartController");
		
		Integer idListSize = idList.size();
		if (request.getQueryString().equals("updateCart")) {
			if (idListSize == countList.size()) {
				cc.updateCart(idList, countList, idListSize);
			} else {
				System.out.println("ERROR : id and count length does not match");
			}
		} else if (request.getQueryString().equals("createCart")) {
			if (idListSize == countList.size()) {
				cc.createCart(idList, countList, idListSize);
			} else {
				System.out.println("ERROR : id and count length does not match");
			}
		}
	}
}
